<?php
session_start();

// 定义文件路径
define('USERS_FILE', 'users.txt');
define('PLATES_FILE', 'plates.txt');
define('SETTINGS_FILE', 'settings.txt');

// 处理用户登出
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: index.php');
    exit;
}

// 处理添加车牌
if (isset($_POST['add_plate']) && isset($_SESSION['user'])) {
    $plateNumber = trim($_POST['plate_number']);
    $plateType = trim($_POST['plate_type']);
    $plateColor = trim($_POST['plate_color']);

    if (empty($plateNumber) || empty($plateType) || empty($plateColor)) {
        $plateError = "请填写完整的车牌信息！";
    } else {
        $plateData = $_SESSION['user'] . "|$plateNumber|$plateType|$plateColor\n";
        if (file_put_contents(PLATES_FILE, $plateData, FILE_APPEND) !== false) {
            header('Location: index.php?view=plates');
            exit;
        } else {
            $plateError = "添加车牌失败，请重试！";
        }
    }
}

// 处理删除车牌
if (isset($_GET['delete_plate']) && isset($_SESSION['user'])) {
    $plateId = (int)$_GET['delete_plate'];
    $plates = file(PLATES_FILE, FILE_IGNORE_NEW_LINES);
    $newPlates = [];

    foreach ($plates as $index => $plate) {
        list($user) = explode('|', $plate);
        if ($user !== $_SESSION['user'] || $index != $plateId) {
            $newPlates[] = $plate;
        }
    }

    if (file_put_contents(PLATES_FILE, implode("\n", $newPlates)) !== false) {
        header('Location: index.php?view=plates');
        exit;
    } else {
        $plateError = "删除车牌失败，请重试！";
    }
}

// 处理设置保存
if (isset($_POST['save_settings']) && isset($_SESSION['user'])) {
    $settings = [
        'sms_url' => $_POST['sms_url'],
        'sms_method' => $_POST['sms_method'],
        'sms_api_key' => $_POST['sms_api_key'],
        'sms_template' => $_POST['sms_template'],
        'smtp_server' => $_POST['smtp_server'],
        'smtp_port' => $_POST['smtp_port'],
        'smtp_user' => $_POST['smtp_user'],
        'smtp_pass' => $_POST['smtp_pass'],
        'smtp_from' => $_POST['smtp_from'],
        'email_template' => $_POST['email_template'],
    ];

    if (file_put_contents(SETTINGS_FILE, serialize($settings)) !== false) {
        header('Location: index.php?view=settings');
        exit;
    } else {
        $settingsError = "保存设置失败，请重试！";
    }
}

// 获取用户的车牌
$userPlates = [];
if (isset($_SESSION['user']) && file_exists(PLATES_FILE)) {
    $plates = file(PLATES_FILE, FILE_IGNORE_NEW_LINES);
    foreach ($plates as $index => $plate) {
        list($user, $number, $type, $color) = explode('|', $plate);
        if ($user === $_SESSION['user']) {
            $userPlates[$index] = ['number' => $number, 'type' => $type, 'color' => $color];
        }
    }
}

// 获取系统设置
$settings = [];
if (file_exists(SETTINGS_FILE)) {
    $settingsData = file_get_contents(SETTINGS_FILE);
    if (!empty($settingsData)) {
        $settings = unserialize($settingsData);
    }
}

// 预设车牌类型
$plateTypes = [
    '普通车牌' => '蓝底白字',
    '临时牌照' => '棕黄底纹黑字黑框线',
    '军用牌照' => '白底红字',
    '武警牌照' => '白底红字',
    '警车牌照' => '白底黑字红"警"字',
    '消防救援车牌照' => '白底黑字红"消"字',
    '摩托车' => '黄底黑字'
];

// 预设车牌颜色
$plateColors = ['蓝色', '黄色', '绿色', '黑色', '白色'];

// 处理用户注册
if (isset($_POST['register'])) {
    $username = trim($_POST['username']);
    $password = password_hash(trim($_POST['password']), PASSWORD_DEFAULT);
    $phone = trim($_POST['phone']);
    $email = trim($_POST['email']);

    if (empty($username) || empty($password) || empty($phone)) {
        $registerError = "用户名、密码和手机号码不能为空！";
    } else {
        $users = file(USERS_FILE, FILE_IGNORE_NEW_LINES);
        $userExists = false;
        foreach ($users as $user) {
            list($savedUser) = explode('|', $user);
            if ($savedUser === $username) {
                $userExists = true;
                break;
            }
        }
        if (!$userExists) {
            $userData = "$username|$password|$phone|$email\n";
            if (file_put_contents(USERS_FILE, $userData, FILE_APPEND) !== false) {
                $_SESSION['user'] = $username;
                $_SESSION['phone'] = $phone;
                $_SESSION['email'] = $email;
                header('Location: index.php');
                exit;
            } else {
                $registerError = "注册失败，请重试！";
            }
        } else {
            $registerError = "用户名已存在！";
        }
    }
}

// 处理用户登录
if (isset($_POST['login'])) {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);

    if (empty($username) || empty($password)) {
        $loginError = "用户名和密码不能为空！";
    } else {
        $users = file(USERS_FILE, FILE_IGNORE_NEW_LINES);
        $loginSuccess = false;

        foreach ($users as $user) {
            list($savedUser, $savedPass, $phone, $email) = explode('|', $user);
            if ($savedUser === $username && password_verify($password, $savedPass)) {
                $_SESSION['user'] = $username;
                $_SESSION['phone'] = $phone;
                $_SESSION['email'] = $email;
                $loginSuccess = true;
                break;
            }
        }

        if ($loginSuccess) {
            header('Location: index.php');
            exit;
        } else {
            $loginError = "用户名或密码错误！";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>多用户挪车二维码管理系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
    <style>
        :root {
            --primary: #3498db;
            --secondary: #2c3e50;
            --success: #27ae60;
            --warning: #f39c12;
            --danger: #e74c3c;
            --light: #ecf0f1;
            --dark: #34495e;
            --gray: #95a5a6;
            --card-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Noto Sans SC', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            padding: 20px;
            color: var(--dark);
            line-height: 1.6;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: var(--card-shadow);
            overflow: hidden;
            min-height: 90vh;
            display: flex;
            flex-direction: column;
        }

        header {
            background: linear-gradient(90deg, var(--primary), var(--secondary));
            color: white;
            padding: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: relative;
            overflow: hidden;
        }

        header::before {
            content: "";
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0) 70%);
            transform: rotate(30deg);
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 15px;
            position: relative;
            z-index: 1;
        }

        .logo i {
            font-size: 2.5rem;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            width: 60px;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .logo h1 {
            font-size: 1.8rem;
            font-weight: 700;
            letter-spacing: 1px;
        }

        .user-actions {
            display: flex;
            gap: 15px;
            align-items: center;
            position: relative;
            z-index: 1;
        }

        .user-actions span {
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: 500;
        }

        .tabs {
            display: flex;
            background: var(--light);
            border-bottom: 1px solid #ddd;
            position: relative;
            z-index: 10;
        }

        .tab {
            padding: 15px 30px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: 600;
            border-bottom: 3px solid transparent;
            color: var(--dark);
            position: relative;
        }

        .tab:hover {
            background: rgba(255, 255, 255, 0.7);
        }

        .tab.active {
            background: white;
            border-bottom: 3px solid var(--primary);
            color: var(--primary);
        }

        .tab-content {
            display: none;
            padding: 30px;
            flex: 1;
        }

        .tab-content.active {
            display: block;
            animation: fadeIn 0.5s ease;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .card {
            background: white;
            border-radius: 12px;
            box-shadow: var(--card-shadow);
            margin-bottom: 25px;
            overflow: hidden;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
        }

        .card-header {
            padding: 18px 25px;
            background: var(--light);
            border-bottom: 1px solid #eee;
            font-weight: 600;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 1.1rem;
        }

        .card-body {
            padding: 25px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--dark);
        }

        .form-control {
            width: 100%;
            padding: 14px 18px;
            border: 1px solid #ddd;
            border-radius: 10px;
            font-size: 16px;
            transition: all 0.3s;
            background: #f9f9f9;
        }

        .form-control:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
            outline: none;
            background: white;
        }

        .form-row {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }

        .form-col {
            flex: 1;
        }

        .btn {
            padding: 14px 28px;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
        }

        .btn:active {
            transform: translateY(1px);
        }

        .btn-primary {
            background: var(--primary);
            color: white;
        }

        .btn-success {
            background: var(--success);
            color: white;
        }

        .btn-warning {
            background: var(--warning);
            color: white;
        }

        .btn-danger {
            background: var(--danger);
            color: white;
        }

        .btn-outline {
            background: transparent;
            border: 2px solid var(--primary);
            color: var(--primary);
        }

        .table-container {
            overflow-x: auto;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }

        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 600px;
        }

        th,
        td {
            padding: 16px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        th {
            background: var(--light);
            font-weight: 600;
            color: var(--dark);
        }

        tr:hover {
            background: #f9f9f9;
        }

        .actions {
            display: flex;
            gap: 10px;
        }

        .qrcode-container {
            display: flex;
            justify-content: center;
            padding: 30px;
            background: #f9f9f9;
            border-radius: 12px;
            margin-top: 20px;
            border: 1px dashed #ddd;
        }

        #qrcode {
            padding: 20px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            border: 1px solid #eee;
        }

        .notification-actions {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-top: 30px;
            flex-wrap: wrap;
        }

        .notification-btn {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 12px;
            padding: 20px 30px;
            background: white;
            border-radius: 12px;
            box-shadow: var(--card-shadow);
            cursor: pointer;
            transition: all 0.3s;
            min-width: 140px;
            text-align: center;
        }

        .notification-btn:hover {
            transform: translateY(-8px);
            box-shadow: 0 12px 25px rgba(0, 0, 0, 0.15);
        }

        .notification-btn i {
            font-size: 2.8rem;
            background: rgba(0, 0, 0, 0.05);
            width: 80px;
            height: 80px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .notification-btn span {
            font-weight: 600;
            font-size: 1.1rem;
        }

        .phone-btn {
            color: var(--primary);
            background: rgba(52, 152, 219, 0.05);
        }

        .sms-btn {
            color: var(--success);
            background: rgba(39, 174, 96, 0.05);
        }

        .email-btn {
            color: var(--warning);
            background: rgba(243, 156, 18, 0.05);
        }

        .login-container {
            max-width: 500px;
            margin: 50px auto;
            background: white;
            border-radius: 15px;
            box-shadow: var(--card-shadow);
            overflow: hidden;
            animation: scaleIn 0.6s ease;
        }

        @keyframes scaleIn {
            from {
                transform: scale(0.95);
                opacity: 0;
            }

            to {
                transform: scale(1);
                opacity: 1;
            }
        }

        .login-tabs {
            display: flex;
            background: var(--light);
        }

        .login-tab {
            flex: 1;
            text-align: center;
            padding: 22px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s;
            color: var(--dark);
            position: relative;
        }

        .login-tab:hover {
            background: rgba(255, 255, 255, 0.7);
        }

        .login-tab.active {
            background: white;
            color: var(--primary);
        }

        .login-tab.active::after {
            content: "";
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 3px;
            background: var(--primary);
        }

        .error-message {
            background: #ffebee;
            color: var(--danger);
            padding: 16px;
            border-radius: 10px;
            margin-bottom: 25px;
            text-align: center;
            font-weight: 500;
            border-left: 4px solid var(--danger);
        }

        .alert {
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 25px;
            text-align: center;
        }

        .alert-info {
            background-color: #e3f2fd;
            border: 1px solid #bbdefb;
            color: #1565c0;
        }

        .alert-success {
            background-color: #e8f5e9;
            border: 1px solid #c8e6c9;
            color: #2e7d32;
        }

        .system-info {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            padding: 25px;
            border-radius: 12px;
            margin-top: 20px;
        }

        footer {
            text-align: center;
            padding: 25px;
            color: var(--gray);
            font-size: 15px;
            background: var(--light);
            border-top: 1px solid #ddd;
            margin-top: auto;
        }

        @media (max-width: 768px) {
            .form-row {
                flex-direction: column;
                gap: 0;
            }

            .notification-actions {
                gap: 15px;
            }

            .tabs {
                flex-wrap: wrap;
            }

            .tab {
                padding: 12px 15px;
                font-size: 14px;
                flex: 1;
                text-align: center;
            }

            header {
                flex-direction: column;
                gap: 15px;
                text-align: center;
            }

            .user-actions {
                flex-direction: column;
            }

            .card-body {
                padding: 20px;
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <?php if (!isset($_SESSION['user'])): ?>
            <!-- 登录/注册页面 -->
            <div class="login-container">
                <div class="login-tabs">
                    <div class="login-tab active" data-tab="login">登录</div>
                    <div class="login-tab" data-tab="register">注册</div>
                </div>

                <div class="card">
                    <div class="card-body">
                        <!-- 登录表单 -->
                        <form id="loginForm" method="POST" style="display: block;">
                            <input type="hidden" name="login" value="1">
                            <?php if (isset($loginError)): ?>
                                <div class="error-message"><?php echo $loginError; ?></div>
                            <?php endif; ?>
                            <div class="form-group">
                                <label for="loginUsername"><i class="fas fa-user"></i> 用户名</label>
                                <input type="text" id="loginUsername" name="username" class="form-control" placeholder="请输入用户名" required>
                            </div>

                            <div class="form-group">
                                <label for="loginPassword"><i class="fas fa-lock"></i> 密码</label>
                                <input type="password" id="loginPassword" name="password" class="form-control" placeholder="请输入密码" required>
                            </div>

                            <button type="submit" class="btn btn-primary" style="width: 100%;">
                                <i class="fas fa-sign-in-alt"></i> 登录
                            </button>
                        </form>

                        <!-- 注册表单 -->
                        <form id="registerForm" method="POST" style="display: none;">
                            <input type="hidden" name="register" value="1">
                            <?php if (isset($registerError)): ?>
                                <div class="error-message"><?php echo $registerError; ?></div>
                            <?php endif; ?>
                            <div class="form-group">
                                <label for="regUsername"><i class="fas fa-user"></i> 用户名</label>
                                <input type="text" id="regUsername" name="username" class="form-control" placeholder="设置用户名" required>
                            </div>

                            <div class="form-group">
                                <label for="regPassword"><i class="fas fa-lock"></i> 密码</label>
                                <input type="password" id="regPassword" name="password" class="form-control" placeholder="设置密码（至少6位）" required>
                            </div>

                            <div class="form-group">
                                <label for="regPhone"><i class="fas fa-mobile-alt"></i> 手机号码</label>
                                <input type="tel" id="regPhone" name="phone" class="form-control" placeholder="请输入手机号码" required>
                            </div>

                            <div class="form-group">
                                <label for="regEmail"><i class="fas fa-envelope"></i> 电子邮箱</label>
                                <input type="email" id="regEmail" name="email" class="form-control" placeholder="请输入电子邮箱（可选）">
                            </div>

                            <button type="submit" class="btn btn-success" style="width: 100%;">
                                <i class="fas fa-user-plus"></i> 注册账号
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <!-- 主系统界面 -->
            <header>
                <div class="logo">
                    <i class="fas fa-car"></i>
                    <h1>挪车二维码管理系统</h1>
                </div>
                <div class="user-actions">
                    <span><i class="fas fa-user"></i> <?php echo htmlspecialchars($_SESSION['user']); ?></span>
                    <a href="?logout" class="btn btn-danger">
                        <i class="fas fa-sign-out-alt"></i> 退出登录
                    </a>
                </div>
            </header>

            <div class="tabs">
                <div class="tab <?php echo (!isset($_GET['view']) || $_GET['view'] === 'qrcode') ? 'active' : ''; ?>" data-tab="qrcode">
                    <i class="fas fa-qrcode"></i> 我的二维码
                </div>
                <div class="tab <?php echo (isset($_GET['view']) && $_GET['view'] === 'plates') ? 'active' : ''; ?>" data-tab="plates">
                    <i class="fas fa-car-alt"></i> 我的车牌
                </div>
                <div class="tab <?php echo (isset($_GET['view']) && $_GET['view'] === 'settings') ? 'active' : ''; ?>" data-tab="settings">
                    <i class="fas fa-cog"></i> 通知设置
                </div>
            </div>

            <!-- 我的二维码 -->
            <div id="qrcode-tab" class="tab-content <?php echo (!isset($_GET['view']) || $_GET['view'] === 'qrcode') ? 'active' : ''; ?>">
                <div class="card">
                    <div class="card-header">
                        <span><i class="fas fa-qrcode"></i> 我的挪车二维码</span>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($userPlates)): ?>
                            <div class="form-group">
                                <label for="selectPlate"><i class="fas fa-car"></i> 选择车牌</label>
                                <select id="selectPlate" class="form-control">
                                    <?php foreach ($userPlates as $index => $plate): ?>
                                        <option value="<?php echo $index; ?>"><?php echo htmlspecialchars($plate['number']) . ' (' . htmlspecialchars($plate['type']) . ')'; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="qrcode-container">
                                <div id="qrcode"></div>
                            </div>

                            <div class="notification-actions">
                                <div class="notification-btn phone-btn" onclick="callUser()">
                                    <i class="fas fa-phone-alt"></i>
                                    <span>拨打电话</span>
                                </div>
                                <div class="notification-btn sms-btn" onclick="smsUser()">
                                    <i class="fas fa-sms"></i>
                                    <span>发送短信</span>
                                </div>
                                <div class="notification-btn email-btn" onclick="emailUser()">
                                    <i class="fas fa-envelope"></i>
                                    <span>发送邮件</span>
                                </div>
                            </div>

                            <div class="form-group" style="margin-top: 30px; text-align: center;">
                                <button class="btn btn-primary" onclick="downloadQRCode()">
                                    <i class="fas fa-download"></i> 下载二维码
                                </button>
                                <button class="btn btn-success" onclick="window.print()">
                                    <i class="fas fa-print"></i> 打印二维码
                                </button>
                            </div>

                            <div class="system-info">
                                <h3><i class="fas fa-info-circle"></i> 使用说明</h3>
                                <p>将生成的二维码贴在车辆挡风玻璃处，当需要挪车时，他人扫码即可通过电话、短信或邮件联系您</p>
                            </div>
                        <?php else: ?>
                            <div class="alert alert-info">
                                <h3><i class="fas fa-info-circle"></i> 提示</h3>
                                <p>您还没有添加任何车牌信息。</p>
                                <p>请先到"我的车牌"页面添加您的车牌信息以生成二维码。</p>
                                <a href="?view=plates" class="btn btn-primary" style="margin-top: 15px;">
                                    <i class="fas fa-plus"></i> 添加车牌
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- 我的车牌 -->
            <div id="plates-tab" class="tab-content <?php echo (isset($_GET['view']) && $_GET['view'] === 'plates') ? 'active' : ''; ?>">
                <?php if (isset($plateError)): ?>
                    <div class="error-message"><?php echo $plateError; ?></div>
                <?php endif; ?>

                <div class="card">
                    <div class="card-header">
                        <span><i class="fas fa-plus-circle"></i> 添加新车牌</span>
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <div class="form-row">
                                <div class="form-col">
                                    <div class="form-group">
                                        <label for="plate_number"><i class="fas fa-car"></i> 车牌号码</label>
                                        <input type="text" id="plate_number" name="plate_number" class="form-control" placeholder="例如：京A12345" required>
                                    </div>
                                </div>
                                <div class="form-col">
                                    <div class="form-group">
                                        <label for="plate_type"><i class="fas fa-tag"></i> 车牌类型</label>
                                        <select id="plate_type" name="plate_type" class="form-control" required>
                                            <option value="">请选择车牌类型</option>
                                            <?php foreach ($plateTypes as $type => $desc): ?>
                                                <option value="<?php echo htmlspecialchars($type); ?>"><?php echo htmlspecialchars($type); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="form-row">
                                <div class="form-col">
                                    <div class="form-group">
                                        <label for="plate_color"><i class="fas fa-palette"></i> 车牌颜色</label>
                                        <select id="plate_color" name="plate_color" class="form-control" required>
                                            <option value="">请选择车牌颜色</option>
                                            <?php foreach ($plateColors as $color): ?>
                                                <option value="<?php echo htmlspecialchars($color); ?>"><?php echo htmlspecialchars($color); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <button type="submit" name="add_plate" class="btn btn-primary">
                                <i class="fas fa-plus"></i> 添加车牌
                            </button>
                        </form>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <span><i class="fas fa-list"></i> 我的车牌列表</span>
                    </div>
                    <div class="card-body">
                        <div class="table-container">
                            <table>
                                <thead>
                                    <tr>
                                        <th>车牌号码</th>
                                        <th>车牌类型</th>
                                        <th>车牌颜色</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($userPlates)): ?>
                                        <tr>
                                            <td colspan="4" style="text-align: center; padding: 30px;">
                                                <i class="fas fa-info-circle" style="color: var(--gray); font-size: 3rem; margin-bottom: 15px;"></i>
                                                <p>暂无车牌信息，请添加您的车牌</p>
                                            </td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($userPlates as $index => $plate): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($plate['number']); ?></td>
                                                <td><?php echo htmlspecialchars($plate['type']); ?></td>
                                                <td><?php echo htmlspecialchars($plate['color']); ?></td>
                                                <td class="actions">
                                                    <a href="?delete_plate=<?php echo $index; ?>" class="btn btn-danger">
                                                        <i class="fas fa-trash"></i> 删除
                                                    </a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 通知设置 -->
            <div id="settings-tab" class="tab-content <?php echo (isset($_GET['view']) && $_GET['view'] === 'settings') ? 'active' : ''; ?>">
                <?php if (isset($settingsError)): ?>
                    <div class="error-message"><?php echo $settingsError; ?></div>
                <?php endif; ?>

                <div class="card">
                    <div class="card-header">
                        <span><i class="fas fa-comment-sms"></i> 短信网关配置</span>
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <div class="form-group">
                                <label for="smsProvider"><i class="fas fa-building"></i> 短信服务提供商</label>
                                <input type="text" id="smsProvider" name="sms_provider" class="form-control" placeholder="例如：阿里云短信、腾讯云短信等" value="<?php echo isset($settings['sms_provider']) ? htmlspecialchars($settings['sms_provider']) : ''; ?>">
                            </div>

                            <div class="form-group">
                                <label for="smsUrl"><i class="fas fa-link"></i> 网关URL</label>
                                <input type="url" id="smsUrl" name="sms_url" class="form-control" placeholder="https://api.sms-provider.com/send" required value="<?php echo isset($settings['sms_url']) ? htmlspecialchars($settings['sms_url']) : ''; ?>">
                            </div>

                            <div class="form-row">
                                <div class="form-col">
                                    <div class="form-group">
                                        <label for="smsMethod"><i class="fas fa-exchange-alt"></i> 请求方法</label>
                                        <select id="smsMethod" name="sms_method" class="form-control" required>
                                            <option value="GET" <?php echo (isset($settings['sms_method']) && $settings['sms_method'] === 'GET') ? 'selected' : ''; ?>>GET</option>
                                            <option value="POST" <?php echo (!isset($settings['sms_method']) || $settings['sms_method'] === 'POST') ? 'selected' : ''; ?>>POST</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-col">
                                    <div class="form-group">
                                        <label for="smsApiKey"><i class="fas fa-key"></i> API密钥</label>
                                        <input type="password" id="smsApiKey" name="sms_api_key" class="form-control" placeholder="请输入API密钥" required value="<?php echo isset($settings['sms_api_key']) ? htmlspecialchars($settings['sms_api_key']) : ''; ?>">
                                    </div>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="smsTemplate"><i class="fas fa-file-alt"></i> 短信模板</label>
                                <textarea id="smsTemplate" name="sms_template" class="form-control" rows="4" placeholder="例如：您的车辆（车牌号：{plate}）需要挪动，请尽快处理。通知人电话：{contact_phone}" required><?php echo isset($settings['sms_template']) ? htmlspecialchars($settings['sms_template']) : '您的车辆（车牌号：{plate}）需要挪动，请尽快处理。通知人电话：{contact_phone}'; ?></textarea>
                                <small class="text-muted">可用变量：{plate} - 车牌号, {contact_phone} - 通知人电话</small>
                            </div>

                            <div class="card" style="margin-top: 30px;">
                                <div class="card-header">
                                    <span><i class="fas fa-envelope"></i> SMTP邮箱设置</span>
                                </div>
                                <div class="card-body">
                                    <div class="form-row">
                                        <div class="form-col">
                                            <div class="form-group">
                                                <label for="smtpServer"><i class="fas fa-server"></i> SMTP服务器</label>
                                                <input type="text" id="smtpServer" name="smtp_server" class="form-control" placeholder="例如：smtp.example.com" required value="<?php echo isset($settings['smtp_server']) ? htmlspecialchars($settings['smtp_server']) : ''; ?>">
                                            </div>
                                        </div>
                                        <div class="form-col">
                                            <div class="form-group">
                                                <label for="smtpPort"><i class="fas fa-plug"></i> 端口</label>
                                                <input type="number" id="smtpPort" name="smtp_port" class="form-control" value="<?php echo isset($settings['smtp_port']) ? htmlspecialchars($settings['smtp_port']) : 465; ?>" required>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="form-row">
                                        <div class="form-col">
                                            <div class="form-group">
                                                <label for="smtpUser"><i class="fas fa-user"></i> 用户名</label>
                                                <input type="text" id="smtpUser" name="smtp_user" class="form-control" placeholder="SMTP用户名" required value="<?php echo isset($settings['smtp_user']) ? htmlspecialchars($settings['smtp_user']) : ''; ?>">
                                            </div>
                                        </div>
                                        <div class="form-col">
                                            <div class="form-group">
                                                <label for="smtpPass"><i class="fas fa-lock"></i> 密码</label>
                                                <input type="password" id="smtpPass" name="smtp_pass" class="form-control" placeholder="SMTP密码" required value="<?php echo isset($settings['smtp_pass']) ? htmlspecialchars($settings['smtp_pass']) : ''; ?>">
                                            </div>
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        <label for="smtpFrom"><i class="fas fa-at"></i> 发件人邮箱</label>
                                        <input type="email" id="smtpFrom" name="smtp_from" class="form-control" placeholder="no-reply@example.com" required value="<?php echo isset($settings['smtp_from']) ? htmlspecialchars($settings['smtp_from']) : ''; ?>">
                                    </div>

                                    <div class="form-group">
                                        <label for="emailTemplate"><i class="fas fa-file-alt"></i> 邮件模板</label>
                                        <textarea id="emailTemplate" name="email_template" class="form-control" rows="6" placeholder="邮件内容模板..." required><?php echo isset($settings['email_template']) ? htmlspecialchars($settings['email_template']) : "尊敬的{name}车主：\n\n您的车辆（车牌号：{plate}）需要挪动，请尽快处理。\n通知人电话：{contact_phone}\n\n感谢您的配合！\n挪车二维码服务"; ?></textarea>
                                        <small class="text-muted">可用变量：{name} - 车主姓名, {plate} - 车牌号, {contact_phone} - 通知人电话</small>
                                    </div>
                                </div>
                            </div>

                            <div style="margin-top: 30px; display: flex; gap: 15px;">
                                <button type="submit" name="save_settings" class="btn btn-primary" style="flex: 1;">
                                    <i class="fas fa-save"></i> 保存设置
                                </button>

                                <button type="button" class="btn btn-success" style="flex: 1;" onclick="testSettings()">
                                    <i class="fas fa-paper-plane"></i> 测试发送
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <script>
        // 登录/注册标签切换
        document.querySelectorAll('.login-tab').forEach(tab => {
            tab.addEventListener('click', function() {
                document.querySelectorAll('.login-tab').forEach(t => t.classList.remove('active'));
                this.classList.add('active');

                const tabId = this.getAttribute('data-tab');
                if (tabId === 'login') {
                    document.getElementById('loginForm').style.display = 'block';
                    document.getElementById('registerForm').style.display = 'none';
                } else {
                    document.getElementById('loginForm').style.display = 'none';
                    document.getElementById('registerForm').style.display = 'block';
                }
            });
        });

        <?php if (isset($_SESSION['user'])): ?>
            // 主系统标签切换
            document.querySelectorAll('.tab').forEach(tab => {
                tab.addEventListener('click', function() {
                    document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                    this.classList.add('active');

                    const tabId = this.getAttribute('data-tab');
                    document.querySelectorAll('.tab-content').forEach(content => {
                        content.classList.remove('active');
                    });

                    document.getElementById(tabId + '-tab').classList.add('active');

                    // 如果是二维码标签，生成二维码
                    if (tabId === 'qrcode') {
                        generateQRCode();
                    }
                });
            });

            // 生成二维码函数
            function generateQRCode() {
                const container = document.getElementById('qrcode');
                container.innerHTML = ''; // 清除旧的二维码

                const plateId = document.getElementById('selectPlate').value;
                const userPhone = "<?php echo $_SESSION['phone'] ?? ''; ?>";

                // 生成二维码内容
                const qrContent = `MOVE_CAR:PHONE:${userPhone}:PLATE:${plateId}`;

                // 使用QRCode.js生成二维码
                try {
                    new QRCode(container, {
                        text: qrContent,
                        width: 220,
                        height: 220,
                        colorDark: "#000000",
                        colorLight: "#ffffff",
                        correctLevel: QRCode.CorrectLevel.H
                    });
                } catch (e) {
                    console.error("生成二维码失败:", e);
                    container.innerHTML = '<div class="error-message">生成二维码失败，请重试</div>';
                }
            }

            // 通知功能
            function callUser() {
                const phone = "<?php echo $_SESSION['phone'] ?? ''; ?>";
                if (confirm(`确定要呼叫 ${phone} 吗？`)) {
                    window.location.href = `tel:${phone}`;
                }
            }

            function smsUser() {
                const phone = "<?php echo $_SESSION['phone'] ?? ''; ?>";
                if (confirm(`确定要给 ${phone} 发送短信吗？`)) {
                    window.location.href = `sms:${phone}`;
                }
            }

            function emailUser() {
                const email = "<?php echo $_SESSION['email'] ?? ''; ?>";
                if (email) {
                    if (confirm(`确定要给 ${email} 发送邮件吗？`)) {
                        window.location.href = `mailto:${email}`;
                    }
                } else {
                    alert("您尚未设置邮箱地址！");
                }
            }

            // 下载二维码
            function downloadQRCode() {
                const canvas = document.querySelector('#qrcode canvas');
                if (canvas) {
                    try {
                        const plateSelect = document.getElementById('selectPlate');
                        const plateText = plateSelect.options[plateSelect.selectedIndex].text.split(' ')[0];

                        const link = document.createElement('a');
                        link.download = `挪车二维码-${plateText}.png`;
                        link.href = canvas.toDataURL('image/png');
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                    } catch (e) {
                        console.error("下载二维码失败:", e);
                        alert("下载二维码失败，请重试");
                    }
                } else {
                    alert("请先生成二维码");
                }
            }

            // 测试设置
            function testSettings() {
                alert("测试发送功能已触发！\n在实际应用中，这里会调用您设置的短信网关或SMTP服务器进行测试。");
            }

            // 初始化时生成二维码
            window.onload = function() {
                <?php if ((!isset($_GET['view']) || $_GET['view'] === 'qrcode') && !empty($userPlates)): ?>
                    generateQRCode();
                <?php endif; ?>

                // 初始化登录/注册标签
                document.querySelector('.login-tab[data-tab="login"]').classList.add('active');
            };

            // 车牌选择更改时重新生成二维码
            if (document.getElementById('selectPlate')) {
                document.getElementById('selectPlate').addEventListener('change', generateQRCode);
            }
        <?php endif; ?>
    </script>
</body>

</html>